package com.ruoyi.web.controller.http;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Http.CommonResult;
import com.ruoyi.system.domain.Http.HttpEntity;
import com.ruoyi.system.domain.Http.InterfaceResult;
import com.ruoyi.system.domain.Http.ResponseData;
import com.ruoyi.system.mapper.InterfaceResultMapper;
import com.ruoyi.system.service.HttpMethodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/util")
public class HttpController {
    @Autowired
    HttpMethodService httpMethodService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private InterfaceResultMapper interfaceResultMapper;

    @PostMapping("/testHttp")
    public CommonResult invoke(@Valid @RequestBody HttpEntity httpEntity, BindingResult bindingResult, HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return CommonResult.failed(errMsg);
        }
        ResponseData responseData = httpMethodService.chooseMethod(httpEntity);
        System.out.println(responseData.getHeaders().toString());
        return CommonResult.success(responseData);
    }
    @PostMapping("/saveTestHttp")
    public CommonResult save(@Valid @RequestBody HttpEntity httpEntity, BindingResult bindingResult, HttpServletResponse response){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        InterfaceResult interfaceResult = new InterfaceResult();
        if (bindingResult.hasErrors()) {
            String errMsg = bindingResult.getFieldError().getDefaultMessage();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return CommonResult.failed(errMsg);
        }
        ResponseData responseData = httpMethodService.chooseMethod(httpEntity);
        System.out.println("httpEntity"+httpEntity.toString());
        //设置操作用户的id
        interfaceResult.setUserId(loginUser.getUser().getUserId());
        //设置接口id（随机数）
        interfaceResult.setResultId(IdUtils.simpleUUID());
        //设置接口名字
        interfaceResult.setInterfaceName(httpEntity.getInterfaceName());
        //设置请求类型（http、https）
        interfaceResult.setType(httpEntity.getType());
        //设置请求方法
        interfaceResult.setMethods(httpEntity.getMethods());
        //设置host
        interfaceResult.setHost(httpEntity.getHost());
        //设置接口地址
        interfaceResult.setApiurl(httpEntity.getApiUrl());
        //设置传入接口头部请求参数
        if (httpEntity.getHeaders().equals("")){
            interfaceResult.setHeaders("{}");
        }
        else {
            interfaceResult.setHeaders(beautifulJson(httpEntity.getHeaders()));
        }
        //设置接口超时时间
        interfaceResult.setTimeout(httpEntity.getTimeOut());
        //设置接口请求参数
        if (httpEntity.getParams().equals("")){
            interfaceResult.setHttpParams("{}");
        }
        else {
            interfaceResult.setHttpParams(beautifulJson(httpEntity.getParams()));
        }
        //设置接口请求体
        interfaceResult.setBody(httpEntity.getBody());
        //设置Content-Type
        Map headers = responseData.getHeaders();
        interfaceResult.setContentType((String) headers.get("Content-Type"));
        //设置Connection
        interfaceResult.setConnection((String) headers.get("Connection"));
        //设置Keep-Alive
        interfaceResult.setKeepAlive((String) headers.get("Keep-Alive"));
        //设置Transfer-Encoding
        interfaceResult.setTransferEncoding((String) headers.get("Transfer-Encoding"));
        //设置error
        List<Map<String, Object>> body = responseData.getBody();
        Map<String, Object> stringObjectMap = body.get(0);
        interfaceResult.setError(String.valueOf(stringObjectMap.get("error")));
        //设置status
        if (stringObjectMap.get("status")==null){
            interfaceResult.setStatus("200");
        }else {
            interfaceResult.setStatus(String.valueOf(stringObjectMap.get("status")));
        }

        //设置时间
        interfaceResult.setResultTime(new Date());

        JSONObject js = null;
        for (Map<String, Object> Map : body) {
             js = new JSONObject(Map);
        }
        //设置returnBody
        String pretty = JSON.toJSONString(js, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        System.out.println(interfaceResult.toString());
        if (stringObjectMap.get("path")==null&&stringObjectMap.get("error")==null&&stringObjectMap.get("timestamp")==null&&stringObjectMap.get("status")==null){
            interfaceResult.setReturnBody(pretty);
        }
        interfaceResultMapper.insertInterfaceResult(interfaceResult);
        return CommonResult.success(responseData);
    }
    public String beautifulJson(String s){
        JSONObject object = JSONObject.parseObject(s);
        String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        return pretty;
    }

}
